package com.yyx.server.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.yyx.server.pojo.Admin;
import com.yyx.server.service.AdminService;
import com.yyx.server.utils.FastDFSUtil;
import com.yyx.server.vo.ResultVo;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * 用户个人中心
 * @author YongXin
 * @date Created in 2021/8/16 21:54
 */
@RestController
public class AdminInfoController {

    @Autowired
    private AdminService adminService;

    @ApiOperation("更新当前用户信息")
    @PutMapping("/admin/info")
    public ResultVo updAdminInfo(@RequestBody Admin admin, Authentication authentication){
        if (adminService.updateById(admin)){
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(admin,null,authentication.getAuthorities()));
            return ResultVo.success("更新成功");
        }
        return ResultVo.error("更新失败");
    }
    @ApiOperation("新增用户")
    @PostMapping("/admin/addAdmin")
    public ResultVo addAdmin(@RequestBody Admin admin){
        admin.setGmtCreate(LocalDateTime.now());
        boolean save = adminService.save(admin);
        if (save) {
            return ResultVo.success("添加成功!");
        }
        return ResultVo.error("添加失败！");
    }


    @ApiOperation("更新用户密码")
    @PutMapping("/admin/pass")
    public ResultVo updAdminPass(@RequestBody Map<String,Object> info){
        String oldPass = (String) info.get("oldPass");
        String pass = (String) info.get("pass");
        Integer adminId = (Integer) info.get("adminId");
        return adminService.updAdminPassword(oldPass,pass,adminId);
    }

    @ApiOperation("更新用户头像")
    @PostMapping("/admin/userface")
    public ResultVo updAdminUserFace(@RequestParam(value = "file",required = false)MultipartFile file, Integer id, Authentication authentication){
        String[] upload = FastDFSUtil.upload(file);
        String url = FastDFSUtil.getTrackerUrl() + upload[0] + "/" + upload[1];
        return adminService.updAdminFace(url,id,authentication);

    }
}
